const fs = require('fs');
const path = require('path');

const getFileStat = require('./libs/fileStat');

// 遍历每个文件夹
const ROOT_FOLDER_PATH = path.join(__dirname, './');
const IMG_FILE_NAME = 'imgs';


// 要整理的每个单元的文件夹
const unitFolders = ['unit_8'];

unitFolders.forEach(folderName => {
  const imgPath = path.join(ROOT_FOLDER_PATH, folderName, IMG_FILE_NAME);
  const imgs = fs.readdirSync(imgPath);
  const handlers = imgs.map(img => {
    const imgPath = path.join(ROOT_FOLDER_PATH, folderName, IMG_FILE_NAME, img);
    return getFileStat(imgPath);
  });
  Promise.all(handlers).then(values => {
    values.sort((first, second) => {
      return first.birthtimeMs * 10000 - second.birthtimeMs * 10000;
    });

    let i = 0;
    values.forEach(item => {
      const { filePath, fileName, fileFolder } = item;
      fs.renameSync(filePath, path.join(fileFolder, `${i+1}.${fileName.split('.')[1]}`));
      i++;
    })
  })
});

